function [Y_demeaned] = Y_demean(Y_all,sample,demean_wave)

% This function demeans Y. Need to be a separate function to facilitate the
% parfor loop. 

if demean_wave==0
    % Demean entire sample
    meanY_all = mean(Y_all);
    Y_demeaned = Y_all - meanY_all; 
else
    % Demean within wave
    sample.mean_wave(sample.opower_paper_wave==3) = mean(Y_all(sample.opower_paper_wave==3));
    sample.mean_wave(sample.opower_paper_wave==6) = mean(Y_all(sample.opower_paper_wave==6));
    sample.mean_wave(sample.opower_paper_wave==7) = mean(Y_all(sample.opower_paper_wave==7));
    Y_demeaned = Y_all - sample.mean_wave; 
end